# plugs/misc.py
#
#

""" misc commands """

__copyright__ = 'this file is in the public domain'

from gozerbot.generic import waitforuser, gozerpopen
from gozerbot.commands import cmnds
from gozerbot.examples import examples
from gozerbot.aliases import aliases
from gozerbot.plughelp import plughelp
import time, os, threading

plughelp.add('misc', 'miscellaneous commands')

def handle_test(bot, ievent):
    """ test .. give test response which is a string of the ircevent """
    ievent.reply(str(ievent))

cmnds.add('test', handle_test, ['USER', 'WEB'])
examples.add('test', 'give test response',' test')

def handle_active(bot, ievent):
    """ active [<minback>] .. show who has been active, default is the 
        last 15 min 
    """
    try:
        minback = int(ievent.args[0])
    except:
        minback = 15
    result = []
    for i in bot.backlog:
        if not i.nick:
            continue
        if i.channel.lower() != ievent.channel.lower():
            continue
        if i.cmnd != 'PRIVMSG':
            continue
        if i.time < time.time()-minback*60:
            continue
        if i.nick not in result:
            result.append(i.nick)
        try:
            result.remove('bot')
        except:
            pass
    if len(result) > 1:
        result.reverse()
        ievent.reply("active in the last %s minutes = %s" % \
(minback," ".join(result)))
    elif len(result) == 1:
        ievent.reply("%s is active" % result[0])
    else:
        ievent.reply("nobody active")

cmnds.add('active', handle_active, ['USER', 'WEB'])
examples.add('active', 'active [<minutesback>] .. show who has been active \
in the last 15 or <minutesback> minutes', '1) active 2) active 600')
aliases.data['a'] = 'active'

def handle_line(bot, ievent):
    """ line .. show activity of last hour """
    now = time.time()
    times = [0]*61
    for i in bot.backlog:
        if not i.channel:
            continue
        if i.channel.lower() != ievent.channel.lower():
            continue
        if int(i.time) < int(now - 3600):
            continue
        try:
            diff = int(now - float(i.time))
        except ValueError:
            continue
        times[int(diff/60)] += 1
    result = ""
    for j in range(61):
        if times[j]:
            result += "%s " % times[j]
        else:
            result += "- "
    result += '(number of lines per minute for the last hour .. \
most recent minute first)'
    ievent.reply(result)

cmnds.add('line', handle_line, ['USER', 'WEB'])
examples.add('line', 'show activity for the last hour', 'line')
aliases.data['l'] = 'line'

# thnx to timp for this one
def handle_dayline(bot, ievent):
    """ dayline .. show activity for last 24 hours """
    now = time.time()
    times = [0]*25
    for i in bot.backlog:
        if not i.channel:
            continue
        if i.channel.lower() != ievent.channel.lower():
            continue
        diff = int(now/1440 - float(i.time)/1440)
        if diff < 25:
            times[diff] += 1
    result = ""
    for j in range(25):
        if times[j]:
            result += "%s " % times[j]
        else:
            result += "- "
    result += ' (nr lines per hour for the last day .. most recent hour first)'
    ievent.reply(result)

cmnds.add('dayline', handle_dayline, ['USER', 'WEB'])
examples.add('dayline', 'show nr of lines spoken in last day', 'dl')
aliases.data['dl'] = 'dayline'

def handle_source(bot, ievent):
    """ source .. show where to fetch the bot source """ 
    ievent.reply("see http://r8.cg.nu .. for mercurial use: hg clone \
http://r8.cg.nu/hg/gozerbot")

cmnds.add('source', handle_source, ['USER', 'WEB'])
examples.add('source', 'show source url', 'source')


def handle_response(bot, ievent):
    """ response .. check if we can get a reply of user """
    ievent.reply("say something so i can see if i can get a \
response from you")
    reply = waitforuser(bot, ievent.nick)
    if not reply:
        ievent.reply("can't get a response")
    else:
        ievent.reply("you said %s" % reply.txt)

cmnds.add('response', handle_response, 'USER')
examples.add('response', 'response test .. see if we can receive a response', \
'response')

def handle_ps(bot, ievent):
    """ ps .. show ps line of the bot """
    args = [""] * 3
    args[0] = 'ps'
    args[1] = 'wwup'
    args[2] = str(os.getpid())
    try:
        proces = gozerpopen(args)
    except Excpetion, ex:
        ievent.reply('error running popen: %s' % str(ex))
        return
    data = proces.fromchild.readlines()
    if not proces.wait():
        result = str(data[1]).strip().split()
        temp1 = "cpu=%s mem=%s vsz=%s rss=%s " % tuple(result[2:6])
        temp2 = "stat=%s started=%s time=%s" % tuple(result[7:10])
        threads = " threads=%s" % str(threading.activeCount())
        ievent.reply(temp1+temp2+threads)
    else:
        ievent.reply('error executing ps')

cmnds.add('ps', handle_ps, ['USER', 'WEB'])
examples.add('ps', 'show ps line of the bot', 'ps')

def handle_time(bot, ievent):
    """ time .. show current time """
    ievent.reply(time.ctime(time.time()))

cmnds.add('time', handle_time, 'USER')
examples.add('time', 'show current time', 'time')
aliases.data['t'] = 'time'
aliases.data['date'] = 'time'
